#include "ImagePrevieWarea.h"
#include <QGridLayout>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMouseEvent>
#include <QFileInfo>
#include <QFileDialog>
#include <QMessageBox>
#include <QInputDialog>
#include <QMediaPlayer>
#include <QVideoFrame>
#include <QVideoSink>
#include "FileExporter.h"
#include <QtConcurrent>
#include <QTimer>

ClickableLabel::ClickableLabel(QWidget* parent, Qt::WindowFlags f)
    : QLabel(parent, f)
{}

ClickableLabel::~ClickableLabel() {}

void ClickableLabel::mouseReleaseEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton)
        emit clicked();
    QLabel::mouseReleaseEvent(event);
}

ImagePreviewArea::ImagePreviewArea(QWidget *parent) 
    : QWidget(parent), m_currentPage(0), m_imagesPerPage(9), m_imageSize(100), m_isLoading(false)
{
    m_futureWatcher = new QFutureWatcher<void>(this);
    connect(m_futureWatcher, &QFutureWatcher<void>::finished, this, [this]() {
        m_isLoading = false;
    });
    
    setupUI();
}

void ImagePreviewArea::setupUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    QWidget *imageWidget = new QWidget(this);
    QGridLayout *imageGrid = new QGridLayout(imageWidget);
    imageGrid->setSpacing(5);
    
    for (int i = 0; i < m_imagesPerPage; ++i) {
        QVBoxLayout *itemLayout = new QVBoxLayout();

        ClickableLabel *imageLabel = new ClickableLabel(this);
        imageLabel->setScaledContents(true);
        imageLabel->setAlignment(Qt::AlignCenter);
        itemLayout->addWidget(imageLabel);

        ClickableLabel *nameLabel = new ClickableLabel(this);
        nameLabel->setAlignment(Qt::AlignCenter);
        nameLabel->setWordWrap(true);
        itemLayout->addWidget(nameLabel);

        m_imageLabels.append(imageLabel);
        m_nameLabels.append(nameLabel);

        imageGrid->addLayout(itemLayout, i / 3, i % 3);
    }
    
    mainLayout->addWidget(imageWidget);

    QHBoxLayout *controlLayout = new QHBoxLayout();
    m_prevButton = new QPushButton("上一页", this);
    m_nextButton = new QPushButton("下一页", this);
    m_pageInfoLabel = new QLabel(this);
    controlLayout->addWidget(m_prevButton);
    controlLayout->addWidget(m_pageInfoLabel);
    controlLayout->addWidget(m_nextButton);
    mainLayout->addLayout(controlLayout);

    m_exportButton = new QPushButton("导出图片", this);
    mainLayout->addWidget(m_exportButton);

    connect(m_prevButton, &QPushButton::clicked, this, &ImagePreviewArea::onPrevClicked);
    connect(m_nextButton, &QPushButton::clicked, this, &ImagePreviewArea::onNextClicked);
    connect(m_exportButton, &QPushButton::clicked, this, &ImagePreviewArea::exportImages);

    for (int i = 0; i < m_imageLabels.size(); ++i) {
        connect(m_imageLabels[i], &ClickableLabel::clicked, this, [this, i]() { onImageClicked(i); });
        connect(m_nameLabels[i], &ClickableLabel::clicked, this, [this, i]() { onImageClicked(i); });
    }

    updateImageSizes();
}

void ImagePreviewArea::setImageList(const QVector<FileInfo>& imageList)
{
    m_imageList = imageList;
    m_currentPage = 0;
    updatePreview();
}

void ImagePreviewArea::updatePreview()
{
    int startIndex = m_currentPage * m_imagesPerPage;
    
    // 先清空所有标签
    for (int i = 0; i < m_imagesPerPage; ++i) {
        m_imageLabels[i]->clear();
        m_imageLabels[i]->setFixedSize(m_imageSize, m_imageSize);
        m_imageLabels[i]->setStyleSheet("background-color: #f0f0f0; border: 1px solid #d0d0d0;");
        m_nameLabels[i]->clear();
    }
    
    // 显示图片和文件名
    for (int i = 0; i < m_imagesPerPage; ++i) {
        if (startIndex + i < m_imageList.size()) {
            const FileInfo& fileInfo = m_imageList[startIndex + i];
            m_nameLabels[i]->setText(fileInfo.fileName);
            
            if (fileInfo.fileType == FileType::Video) {
                m_imageLabels[i]->setText("Video");
            } else {
                // 检查缓存
                if (m_pixmapCache.contains(fileInfo.filePath)) {
                    m_imageLabels[i]->setPixmap(m_pixmapCache[fileInfo.filePath]);
                } else {
                    m_imageLabels[i]->setText("Loading...");
                    loadImageAsync(startIndex + i, i);
                }
            }
        }
    }
    
    // 更新页面信息
    int totalPages = (m_imageList.size() + m_imagesPerPage - 1) / m_imagesPerPage;
    m_pageInfoLabel->setText(QString("%1 / %2").arg(m_currentPage + 1).arg(totalPages));
    m_prevButton->setEnabled(m_currentPage > 0);
    m_nextButton->setEnabled(m_currentPage < totalPages - 1);
}

void ImagePreviewArea::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    
    // 使用 QTimer 延迟更新，避免频繁调整导致的性能问题
    static QTimer resizeTimer;
    resizeTimer.setSingleShot(true);
    
    disconnect(&resizeTimer, nullptr, nullptr, nullptr);
    connect(&resizeTimer, &QTimer::timeout, this, &ImagePreviewArea::updateImageSizes);
    
    resizeTimer.start(100);  // 100ms 延迟
}

void ImagePreviewArea::updateImageSizes()
{
    // 计算可用空间，考虑边距和其他控件的空间
    int availableWidth = width() - 40;  // 增加左右边距
    int availableHeight = height() - 120;  // 增加底部预留空间
    
    // 计算每个图片的最大尺寸
    int gridSize = 3;  // 3x3网格
    int spacing = 10;  // 网格间距
    
    int maxWidth = (availableWidth - (gridSize - 1) * spacing) / gridSize;
    int maxHeight = (availableHeight - (gridSize - 1) * spacing) / gridSize;
    
    // 取较小值确保图片完全显示
    int newImageSize = qMin(maxWidth, maxHeight);
    
    // 设置最小和最大限制，增加最大尺寸限制
    newImageSize = qMax(100, qMin(newImageSize, 500));  // 增加最大尺寸到500px
    
    // 只有当尺寸变化超过阈值时才更新
    if (abs(newImageSize - m_imageSize) > 5) {
        m_imageSize = newImageSize;
        
        // 更新所有标签的大小
        for (ClickableLabel *label : m_imageLabels) {
            label->setFixedSize(m_imageSize, m_imageSize);
        }
        
        // 清除缓存并强制重新加载图片
        m_pixmapCache.clear();
        updatePreview();
    }
}

void ImagePreviewArea::onPrevClicked()
{
    if (m_currentPage > 0) {
        --m_currentPage;
        updatePreview();
    }
}

void ImagePreviewArea::onNextClicked()
{
    int totalPages = (m_imageList.size() + m_imagesPerPage - 1) / m_imagesPerPage;
    if (m_currentPage < totalPages - 1) {
        ++m_currentPage;
        updatePreview();
    }
}

void ImagePreviewArea::onImageClicked(int index)
{
    int actualIndex = m_currentPage * m_imagesPerPage + index;
    if (actualIndex < m_imageList.size()) {
        // 移除清除缓存的代码
        // m_pixmapCache.clear();  // 删除这行
        emit imageSelected(m_imageList[actualIndex]);
    }
}

void ImagePreviewArea::exportImages()
{
    if (m_imageList.isEmpty()) {
        QMessageBox::warning(this, "警告", "没有可导出的图片");
        return;
    }

    QString exportPath = QFileDialog::getExistingDirectory(this, "选择导出路径", QDir::homePath());
    if (exportPath.isEmpty()) {
        return;
    }

    QString prefix = QInputDialog::getText(this, "输入前缀", "请输入导出文件的命名前缀:");
    if (prefix.isEmpty()) {
        return;
    }

    // 添加删除原文件的选项
    QMessageBox::StandardButton reply = QMessageBox::question(this, 
        "删除原文件", 
        "是否在导出后删除原文件？",
        QMessageBox::Yes | QMessageBox::No,
        QMessageBox::No);
    
    bool deleteOriginal = (reply == QMessageBox::Yes);

    FileExporter exporter;
    QString errorMessage;
    bool success = exporter.exportFiles(m_imageList, exportPath, prefix, errorMessage, deleteOriginal);

    if (success) {
        QString message = "图片已成功导出";
        if (deleteOriginal) {
            message += "，原文件已删除";
        }
        QMessageBox::information(this, "导出成功", message);
        
        // 如果删除了原文件，需要通知父窗口刷新文件列表
        if (deleteOriginal) {
            emit imageSelected(FileInfo());  // 发送空的 FileInfo 来触发刷新
        }
    } else {
        QMessageBox::warning(this, "导出失败", "导出过程中发生错误:\n" + errorMessage);
    }
}

void ImagePreviewArea::loadImageAsync(int imageIndex, int labelIndex)
{
    if (imageIndex >= m_imageList.size()) return;
    
    const FileInfo& fileInfo = m_imageList[imageIndex];
    if (fileInfo.fileType != FileType::Image) return;
    
    auto future = QtConcurrent::run([this, fileInfo, labelIndex]() {
        QPixmap originalPixmap(fileInfo.filePath);
        if (!originalPixmap.isNull()) {
            QPixmap scaledPixmap;
            
            // 根据原图尺寸和目标尺寸选择合适的缩放方式
            if (originalPixmap.width() > m_imageSize || originalPixmap.height() > m_imageSize) {
                // 使用高质量缩放，保持纵横比
                scaledPixmap = originalPixmap.scaled(
                    QSize(m_imageSize, m_imageSize),
                    Qt::KeepAspectRatio,
                    Qt::SmoothTransformation
                );
            } else {
                // 如果原图较小，直接使用原图
                scaledPixmap = originalPixmap;
            }
            
            // 在主线程中更新UI
            QMetaObject::invokeMethod(this, [this, scaledPixmap, fileInfo, labelIndex]() {
                m_pixmapCache.insert(fileInfo.filePath, scaledPixmap);
                if (labelIndex < m_imageLabels.size()) {
                    m_imageLabels[labelIndex]->setPixmap(scaledPixmap);
                }
            }, Qt::QueuedConnection);
        }
    });
    
    m_runningTasks.append(future);
    
    // 清理已完成的任务
    m_runningTasks.erase(
        std::remove_if(m_runningTasks.begin(), m_runningTasks.end(),
            [](const QFuture<void>& f) { return f.isFinished(); }),
        m_runningTasks.end()
    );
}

// 在析构函数中等待所有任务完成
ImagePreviewArea::~ImagePreviewArea()
{
    for (auto& future : m_runningTasks) {
        future.waitForFinished();
    }
}

